<template>
  <div class="app-container">
    <el-card>
      <div slot="header">
        <el-search-form label-width="90px" @search="onSearch" @reset="onReset">
          <el-form-item label="DictName">
            <el-input
              clearable
              size="small"
              v-model="searchBody.dictName"
              class="el-input__small"
            ></el-input>
          </el-form-item>
        </el-search-form>
      </div>
      <div class="pagination-box__withButton">
        <div>
          <el-button type="primary" size="small" @click="handleClick('add')"
            >新增数据</el-button
          >
        </div>
        <el-pagination
          small
          @current-change="handleCurrentChange('list', $event)"
          @size-change="handleSizeChange('list', $event)"
          :current-page="pageNo"
          :page-sizes="pageSizeOpts"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </div>
      <div class="have-pagination-container">
        <el-table v-loading="loading.list" :data="list" border>
          <el-table-column
            prop="id"
            label="ID"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="dictName"
            label="DictName"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="dictType"
            label="DictType"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="createDate"
            label="创建时间"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick('updateValue', scope.row)"
                >配置数据</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleClick('remove', scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
        <el-pagination
          small
          @current-change="handleCurrentChange('list', $event)"
          @size-change="handleSizeChange('list', $event)"
          :current-page="pageNo"
          :page-sizes="pageSizeOpts"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="新增数据"
      :visible.sync="updateDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="updateForm"
        label-width="100px"
        :rules="updateFormRule"
        :model="updateForm"
      >
        <el-form-item label="DictName" prop="dictName">
          <el-input
            size="small"
            v-model="updateForm.dictName"
            class="el-input__small"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="DictType" prop="dictType">
          <el-input
            size="small"
            v-model="updateForm.dictType"
            class="el-input__small"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            size="small"
            class="el-input__small"
            v-model="updateForm.status"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="updateDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSure('updateValue')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="编辑数据"
      :visible.sync="updateChildDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="updateChildForm"
        label-width="100px"
        :model="updateChildForm"
        :rules="updateChildFormRule"
      >
        <el-form-item label="DictLabel" prop="dictLabel">
          <el-input
            v-model="updateChildForm.dictLabel"
            class="el-input__small"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="DictValue" prop="dictValue">
          <el-input
            v-model="updateChildForm.dictValue"
            class="el-input__small"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="是否默认" prop="isDefault">
          <el-select
            class="el-input__small"
            v-model="updateChildForm.isDefault"
            placeholder="请选择"
          >
            <el-option
              v-for="item in isDefaultOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="dictSort">
          <el-input
            v-model="updateChildForm.dictSort"
            class="el-input__small"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="updateChildForm.remark"
            class="el-input__medium"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="updateChildDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSure('updateChild')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="配置数据"
      :visible.sync="configDialog"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="pagination-box__withButton">
        <div>
          <el-form
            label-width="100px"
            ref="updateForm2"
            inline
            :rules="updateFormRule"
            :model="updateForm"
          >
            <el-form-item label="DictName" prop="dictName">
              <el-input
                size="small"
                v-model="updateForm.dictName"
                class="el-input__small"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>

            <el-form-item label="DictType" prop="dictType">
              <el-input
                size="small"
                v-model="updateForm.dictType"
                class="el-input__small"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                size="small"
                class="el-input__small"
                v-model="updateForm.status"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button
            size="small"
            @click="handleClick('updateChild')"
            type="primary"
            >添加</el-button
          >
        </div>
      </div>
      <!-- 二级节点value列表 -->
      <div class="have-pagination-container">
        <el-table border v-loading="loading.childList" :data="childList">
          <el-table-column prop="dictLabel" label="DictLabel"></el-table-column>
          <el-table-column prop="dictValue" label="DictValue"></el-table-column>
          <el-table-column prop="isDefault" label="是否默认"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column prop="createDate" label="创建时间"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick('updateChild', scope.row)"
                >修改</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleClick('removeChild', scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
        <el-pagination
          @current-change="handleCurrentChange('childList', $event)"
          @size-change="handleSizeChange('childList', $event)"
          :current-page.sync="childPageNo"
          :page-size="childPageSize"
          :page-sizes="pageSizeOpts"
          layout="total, sizes, prev, pager, next"
          :total="childTotalCount"
        >
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="configDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSure('updateValue')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysDict_list,
  sysDict_delete,
  sysDict_update,
  sysDict_add,
  sysDict_childList,
  sysDict_childDelete,
  sysDict_childUpdate,
  sysDict_childAdd,
} from "@/api/dataDict";
import { requiredFormValidate } from "@/utils/validate";

const getDefaultUpdateForm = () => ({
  dictName: null,
  dictType: null,
  status: "1",
});
const getDefaultUpdateChildForm = (dictType) => ({
  dictType,
  dictLabel: null,
  dictValue: null,
  isDefault: "N",
  dictSort: 0,
  remark: null,
});
const getDefaultSearchBody = () => ({
  dictName: null,
});
export default {
  data() {
    return {
      handleType: "",
      refName: "",
      pageNo: 1,
      pageSize: 20,
      totalCount: 0,
      pageSizeOpts: [20, 50, 100, 300, 500],
      childPageNo: 1,
      childPageSize: 20,
      childTotalCount: 0,
      loading: {
        list: false,
        childList: false,
      },
      configDialog: false,
      updateDialog: false,
      updateChildDialog: false,
      list: [],
      dictType: null,
      updateFormRule: {
        dictName: [
          {
            required: true,
            validator: requiredFormValidate,
            trigger: ["change", "blur"],
          },
        ],
        dictType: [
          {
            required: true,
            validator: requiredFormValidate,
            trigger: ["change", "blur"],
          },
        ],
      },
      updateChildFormRule: {
        dictLabel: [
          {
            required: true,
            validator: requiredFormValidate,
            trigger: ["change", "blur"],
          },
        ],
        dictValue: [
          {
            required: true,
            validator: requiredFormValidate,
            trigger: ["change", "blur"],
          },
        ],
      },
      childList: [],
      updateForm: getDefaultUpdateForm(),
      updateChildForm: getDefaultUpdateChildForm(),
      searchBody: getDefaultSearchBody(),
      isDefaultOptions: [
        {
          value: "Y",
          label: "是",
        },
        {
          value: "N",
          label: "否",
        },
      ],
      statusOptions: [
        {
          value: "1",
          label: "启用",
        },
        {
          value: "0",
          label: "禁用",
        },
      ],
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.loading.list = true;
      sysDict_list({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...this.searchBody,
      }).then(({ result = {} }) => {
        this.list = result.data;
        this.totalCount = result.totalCount;
        this.loading.list = false;
      });
    },
    // 获取子级列表
    getChildData() {
      this.loading.childList = true;
      sysDict_childList({
        pageNo: this.childPageNo,
        pageSize: this.childPageSize,
        dictType: this.dictType,
      })
        .then(({ result = {} }) => {
          this.childList = result.data;
          this.childTotalCount = result.totalCount;
          this.loading.childList = false;
        })
        .catch(() => {
          this.loading.childList = false;
        });
    },
    handleSizeChange(type, val) {
      switch (type) {
        case "list":
          this.pageSize = val;
          this.getData();
          break;
        case "childList":
          this.childPageSize = val;
          this.getChildData();
          break;
      }
    },
    handleCurrentChange(type, val) {
      switch (type) {
        case "list":
          this.pageNo = val;
          this.getData();
          break;
        case "childList":
          this.childPageNo = val;
          this.getChildData();
          break;
      }
    },
    onSearch() {
      this.pageNo = 1;
      this.getData();
    },
    onReset() {
      this.pageNo = 1;
      this.searchBody = getDefaultSearchBody();
      this.getData();
    },

    handleClick(type, row) {
      this.handleType = type;
      switch (type) {
        case "add":
          this.refName = "updateForm"; //控制form
          this.updateForm = getDefaultUpdateForm();
          this.updateDialog = true;
          this.$nextTick(() => {
            this.$refs.updateForm.clearValidate();
          });
          break;
        case "updateValue":
          this.refName = "updateForm2"; //控制form
          this.configDialog = true;
          this.$nextTick(() => {
            this.$refs.updateForm2.clearValidate();
          });
          this.dictType = row.dictType;
          this.updateForm = Object.assign({}, row);
          this.getChildData();
          break;
        case "updateChild":
          this.updateChildDialog = true;
          this.updateChildForm = row
            ? Object.assign({}, row)
            : getDefaultUpdateChildForm(this.dictType);
          this.$nextTick(() => {
            this.$refs.updateChildForm.clearValidate();
          });
          break;
        case "removeChild":
          this.$confirm(`是否要删除该子数据？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            sysDict_childDelete({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getChildData();
            });
          });
          break;
        case "remove":
          this.$confirm(`是否要删除该子数据？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            sysDict_delete({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });
          break;
        default:
          return;
      }
    },
    handleSure(type) {
      switch (type) {
        case "add":
          break;
        case "updateValue":
          this.$refs[this.refName].validate((valid) => {
            if (valid) {
              let fn = this.updateForm.id ? sysDict_update : sysDict_add;
              fn(this.updateForm).then((res) => {
                this.$message.success(res.msg || "操作成功");
                this.getData();
                if (this.refName == "updateForm") {
                  this.updateDialog = false;
                } else {
                  this.configDialog = false;
                }
              });
            } else {
              return false;
            }
          });
          break;
        case "updateChild":
          this.$refs.updateChildForm.validate((valid) => {
            if (valid) {
              let fn = this.updateChildForm.id
                ? sysDict_childUpdate
                : sysDict_childAdd;
              fn(this.updateChildForm).then((res) => {
                this.$message.success(res.msg || "操作成功");
                this.getChildData();
                this.updateChildDialog = false;
              });
            } else {
              return false;
            }
          });
          break;
        default:
          return;
      }
    },
  },
};
</script>
